package com.terry.activity.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.terry.activity.bean.EnrollModel;
import com.terry.activity.bean.constant.ErrorCode;
import com.terry.activity.bean.exception.DataAlreadyExistException;
import com.terry.activity.bean.exception.WechatAuthException;
import com.terry.activity.bean.message.ResponseMsg;
import com.terry.activity.controller.base.BaseController;
import com.terry.activity.dao.IEnrollDao;
import com.terry.activity.service.IEnrollService;
import org.apache.commons.lang3.RandomStringUtils;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Create On 18/4/22.
 *
 * @author TerrySolar
 */
@Controller
@RequestMapping(value = "/enroll")
public class EnrollController extends BaseController {


    @Resource
    private IEnrollService enrollService;

    @RequestMapping(value = "/submit", method = RequestMethod.POST)
    @ResponseBody
    @CrossOrigin
    public ResponseMsg handleEnroll(@RequestBody EnrollModel enroll, HttpServletRequest request) throws WechatAuthException, DataAlreadyExistException {
        // 断言微信授权
        assertWechatAuth(request);

        enroll.setOpenId(OPEN_ID);

        enrollService.enroll(enroll);

        return responseOK();
    }


    @ResponseBody
    @RequestMapping(value = "/check", method = RequestMethod.GET)
    public ResponseMsg retrieveEnroll(HttpServletRequest request) throws WechatAuthException {

        assertWechatAuth(request);

        EnrollModel enroll = enrollService.retrieveEnroll(OPEN_ID);

        if (enroll == null) {
            return responseError(ErrorCode.ENROLL_NO_RECORD, "not enroll yet");
        }

        return responseJson((JSONObject) JSON.toJSON(enroll));

    }


}
